package com.xiedafeng.www.util;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

public class DeleteUtil<T,E,X> {
    /*
    可以通过searchid查找主键id进行删除，方便简洁
     */

    public void delete(T t,int id) throws SQLException {
        String sql="delete from "+t.getClass().getSimpleName()+" where id = ?";
        DataSource dataSource=new DataSourceUtil();
        Connection connection = null;
        PreparedStatement preparedstatement=null;
        try {
            connection = dataSource.getConnection();
            preparedstatement = connection.prepareStatement(sql);
            preparedstatement.setInt(1,id);
            preparedstatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        finally {
            connection.close();
            JdbcUtil.close(preparedstatement);
        }
    }
    /*
    参数的意义和封装的search那里差不多，请前往那里查看，
     */
    public void deleteRelation(T t, E e, int tid, int eid, X x, Map condition) throws SQLException {
        StringBuilder sql;
        if (x==null) {
            sql = new StringBuilder("delete from " + t.getClass().getSimpleName() + e.getClass().getSimpleName() + " where " +
                    t.getClass().getSimpleName() + "id = ? and " + e.getClass().getSimpleName() + "id = ?");
        }
        else {
            sql = new StringBuilder("delete from " + x.getClass().getSimpleName() + " where " +
                    t.getClass().getSimpleName() + "id = ? and " + e.getClass().getSimpleName() + "id = ?");
        }
        Object[] keys = new Object[0];
        if (condition.size()!=0){
            keys=condition.keySet().toArray();
            for (Object key : keys) {
                sql.append(" and ").append(key).append(" = ?");
            }
        }
        DataSource dataSource=new DataSourceUtil();
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        try {
            connection = dataSource.getConnection();
            preparedStatement = connection.prepareStatement(sql.toString());
            preparedStatement.setInt(1,tid);
            preparedStatement.setInt(2,eid);
            for (int i = 0; i < keys.length; i++) {
                preparedStatement.setObject(i+3,condition.get(keys[i]));
            }
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        finally {
            connection.close();
            JdbcUtil.close(preparedStatement);
        }
    }
}
